import java.sql.SQLException;
import java.util.Properties;

import javax.jws.WebService;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@WebService(targetNamespace="http://localhost:63081/sendOrder")
public class SendOrderService {

	public String sendOrder(String projectID, String partner) {

		Project p = ProjectContainer.getInstance().getProject(projectID);
		DAO dao = new DAO();
		Order order = new Order();
		order.setCompany(partner);

		try {
			order = dao.getMaterial(projectID, partner);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String subject = "Order for " + order.getOffer();
		
		String message = "Dear " + order.getContact() + ",\n"
				+ "We would like to order " + order.getAmount() + " " + order.getUnit() + " of " + order.getOffer() + ".\n"
				+ "To be delivered at the 20th of September to the following address: " + p.getAddress() + ".\n"
				+ "If you have any questions, do not hesitate to contact us.\n\nKind regards,\nComnpanyXY";
		
		String from = "companyXY@localhost";
		
		String out = "Order sent successfully";
		
		try {
			sendMail(order.getMailAddress(), subject, message, from);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			out = "Unable to send order";
		}

		return out;
	}

	public static void sendMail( String recipient, String subject, String message, String from )throws MessagingException {
		Properties props = new Properties();
		props.put( "mail.smtp.host", "localhost" );
		props.put("mail.smtp.port", "25");
		Session session = Session.getDefaultInstance( props );
		Message msg = new MimeMessage( session );
		InternetAddress addressFrom = new InternetAddress( from );
		msg.setFrom( addressFrom );
		InternetAddress addressTo = new InternetAddress( recipient );
		msg.setRecipient( Message.RecipientType.TO, addressTo );
		msg.setSubject( subject );
		msg.setContent( message, "text/plain" );
		Transport.send( msg );
	}
}
